const app = getApp()

Page({
  data: {
    historyList: []
  },

  onLoad() {
    this.loadHistory()
  },

  onShow() {
    this.loadHistory()
  },

  // 加载播放历史
  loadHistory() {
    const userInfo = app.globalData.userInfo
    if (!userInfo) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      })
      setTimeout(() => {
        wx.navigateBack()
      }, 1500)
      return
    }

    const historyList = app.globalData.playHistory || []
    
    // 格式化播放时间
    const formattedList = historyList.map(item => ({
      ...item,
      playTime: this.formatPlayTime(item.playTime)
    }))
    
    this.setData({
      historyList: formattedList
    })
  },

  // 播放音乐
  playMusic(e) {
    const music = e.currentTarget.dataset.music
    
    // 跳转到播放器页面
    wx.navigateTo({
      url: `/pages/player/player?musicId=${music.id}&name=${encodeURIComponent(music.name)}&artist=${encodeURIComponent(music.artist)}&cover=${encodeURIComponent(music.cover)}&url=${encodeURIComponent(music.url)}`
    })
  },

  // 删除单个历史记录
  deleteHistory(e) {
    e.stopPropagation()
    const { id, index } = e.currentTarget.dataset
    
    wx.showModal({
      title: '确认删除',
      content: '确定要删除这条播放记录吗？',
      success: (res) => {
        if (res.confirm) {
          const app = getApp()
          let historyList = app.globalData.playHistory || []
          
          // 根据id删除记录
          historyList = historyList.filter(item => item.id !== id)
          
          // 更新全局数据和本地存储
          app.globalData.playHistory = historyList
          wx.setStorageSync('playHistory', historyList)
          
          // 重新加载数据
          this.loadHistory()
          
          wx.showToast({
            title: '删除成功',
            icon: 'success'
          })
        }
      }
    })
  },

  // 清空所有播放历史
  clearAllHistory() {
    wx.showModal({
      title: '确认清空',
      content: '确定要清空所有播放历史吗？',
      success: (res) => {
        if (res.confirm) {
          const app = getApp()
          
          // 清空历史记录
          app.globalData.playHistory = []
          wx.removeStorageSync('playHistory')
          
          // 更新页面数据
          this.setData({
            historyList: []
          })
          
          wx.showToast({
            title: '清空成功',
            icon: 'success'
          })
        }
      }
    })
  },

  // 格式化播放时间
  formatPlayTime(timestamp) {
    const date = new Date(timestamp)
    const now = new Date()
    const diff = now - date
    
    if (diff < 60000) { // 1分钟内
      return '刚刚'
    } else if (diff < 3600000) { // 1小时内
      return `${Math.floor(diff / 60000)}分钟前`
    } else if (diff < 86400000) { // 24小时内
      return `${Math.floor(diff / 3600000)}小时前`
    } else {
      return `${date.getMonth() + 1}月${date.getDate()}日`
    }
  }
})